package com.atguigu.yygh.user.service.impl;


import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.enums.StatusEnum;
import com.atguigu.yygh.exception.YYGHException;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.utils.JwtHelper;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-04-22
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {

       //1.获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.对手机号和验证码进行非空验证
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YYGHException(20001,"数据为空");
        }

      //3.TODO: 验证码验证
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){
            throw new YYGHException(20001,"验证码有误");
        }
        UserInfo result = null;
        if(StringUtils.isEmpty(loginVo.getOpenid())){
            //4.是否是首次登录，如果是首次登录，保存用户信息
            QueryWrapper<UserInfo> userInfoQueryWrapper=new QueryWrapper<UserInfo>();
            userInfoQueryWrapper.eq("phone", phone);
            result = userInfoMapper.selectOne(userInfoQueryWrapper);
            if(result == null){
                result=new UserInfo();
                result.setPhone(phone);
                userInfoMapper.insert(result);
                result.setStatus(1);
            }
            //5.验证用户的状态:
            Integer status = result.getStatus();
            if(status == 0){
                throw new YYGHException(20001,"用户已锁定");
            }

        }else{
           //微信强制绑定手机号
            QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
            queryWrapper.eq("openid",loginVo.getOpenid());
            result = baseMapper.selectOne(queryWrapper);

            QueryWrapper<UserInfo> queryWrapper2=new QueryWrapper<UserInfo>();
            queryWrapper2.eq("phone",phone);
            UserInfo result2 = baseMapper.selectOne(queryWrapper2);

            if(result2 == null){
                result.setPhone(loginVo.getPhone());
                baseMapper.updateById(result);
            }else{
                result2.setOpenid(loginVo.getOpenid());
                result2.setNickName(result.getNickName());
                baseMapper.updateById(result2);
                baseMapper.deleteById(result.getId());
            }

            //5.验证用户的状态:
            Integer status = result2.getStatus();
            if(status == 0){
                throw new YYGHException(20001,"用户已锁定");
            }

        }



        //6.返回给浏览器的用户信息
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = result.getName();

        if(StringUtils.isEmpty(name)) {
            name = result.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = result.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(result.getId(), name);
        map.put("token", token);
        return map;
    }


    @Override
    public UserInfo selectById(Long userId) {
        UserInfo userInfo1 = baseMapper.selectById(userId);
        userInfo1.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo1.getAuthStatus()));
        return userInfo1;
    }

    @Override
    public void updateUserInfo(Long userId, UserAuthVo userAuthVo) {
       // UserInfo userInfo1 = baseMapper.selectById(userId);
        UserInfo userInfo1=new UserInfo();
        userInfo1.setId(userId);
        userInfo1.setName(userAuthVo.getName());
        userInfo1.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo1.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo1.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo1.setAuthStatus(1);
        baseMapper.updateById(userInfo1);
    }

    @Override
    public Page<UserInfo> getUserPageByCondition(Integer page, Integer limit, UserInfoQueryVo userInfoQueryVo) {

        Page<UserInfo> page1=new Page<UserInfo>(page,limit);
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
        String keyword = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态

        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间

            if(!StringUtils.isEmpty(keyword)){
            queryWrapper.like("name",keyword).or().eq("phone",keyword);
        }

        if(!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            queryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }
        Page<UserInfo> userInfoPage = baseMapper.selectPage(page1, queryWrapper);
        for (UserInfo record : userInfoPage.getRecords()) {
            this.packageUserInfo(record);
        }
        return userInfoPage;
    }


    @Override
    public void updateStatus(Long id, Integer status) {
       if(status.intValue() == 0 || status.intValue() == 1){
           UserInfo userInfo1=new UserInfo();
           userInfo1.setId(id);
           userInfo1.setStatus(status);
           baseMapper.updateById(userInfo1);
       }
    }

    @Override
    public Map<String, Object> getUserInfoAndPatientList(Integer id) {
        Map<String,Object> map = new HashMap<>();

        //根据userid查询用户信息
        UserInfo userInfo = baseMapper.selectById(id);
        this.packageUserInfo(userInfo);

        map.put("userInfo",userInfo);
        QueryWrapper<Patient> queryWrapper=new QueryWrapper<Patient>();
        queryWrapper.eq("user_id",id);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.selectList(queryWrapper);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
           // UserInfo userInfo = baseMapper.selectById(userId);
            UserInfo userInfo=new UserInfo();
            userInfo.setId(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private void packageUserInfo(UserInfo record) {
        record.getParam().put("statusString", StatusEnum.getStatusStringByStatus(record.getStatus()));
        record.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(record.getAuthStatus()));
    }

}
